// 网络请求错误处理
import Router from "umi/router";
import { loginServer } from "dcloud-utils"
import { Toast } from "antd-mobile";
import md5 from 'md5';
import { JSEncrypt } from 'jsencrypt';
import CryptoJS from 'crypto-js'

// 公钥
let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbtd4Z4Cwc1aD/CmQ8/EepGyoPENNCI50z+zsEayR79Z9VNGPudQTpC3Dk1vWPcK3GjYJj8gHf7XGVpfQVYC6fG3JxlgjaSIbxN5prO1HgARFt8JCC4LS/y7TKIaMPRFdYUx3CJ6JiDBLZN0SaKMwWvk75CWuoVPCtkn3Idp87EQIDAQAB';
// 私钥
let privateKey='MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL9PAc0Zyq0F+cK7+NwouyoBR39+bUhNA1ka1mQa0dKBWWo9be1VXV0NSlsMkmzeUU8IGVfKmH+QF5cMVRmbVRXGm8svKkTvjIKTwdjQehNBJGWUz3aFGzebTSTmFHYEL5DkptLdG+qoUNE4jlgNYC4Ub/8366ZZzZb1aTbK1wrTAgMBAAECgYEAltRdoS0ShDPP5N56qGlclxOHIVe2JWjCmP/1w9r5TrQ4oPBpuNKy12hhFUPmNftZs6u4/2R1sy0RzD8m4Rd8jl1Q11oUoHZVNNDrm/0Ni0mTMm6rB7OMW819XKdC2gi/zc1E5ESUQ317BoOt1yiGTuxUMq/b7FM2bENemEdNo3ECQQD4RgVCNBzIkMjOuGRh+m6pY8YDbXLR3dENqNIyYs/2DbxUB07DvOxRp/UOPmapfC8Lpc+mpWHEuJcck9Y7RzDtAkEAxUMml/jKOssJcA4O2c5PIbassrMgxTl1w7CelQ7B6Vc3rgKHh77GIDT2xH7CTPa3lkZ/483Icjptrgg44rByvwJAEFmsJvv/mUXPs615DurLNuSXOcqPcTrGdbvUe/T99RpaeL4ydbmPZqFFBjcd07OV9ZJp5nOlyKrPaNZjmWvK0QJAAm6ZgzYmCCOIskD6HeVVRG0kI+/hb40NzqPW0K+l5GKW5SZS1XGcr7j3ceS+MIS6Lrgfy4c1+XKO955SVTknsQJBAM772Pj3f49L4M1xxzuilo04F8nNlFwsOfsMT+chmVknA1P3m/kCU9OszOj2sQcFUPq71ipLSzYdJAo5vsa4jkc=';
let jsonPrams={};

export default class httpUtilConfig {
    /**
     * 请求头配置
     */

    getHeaders(type = 'json', parmas) {
        const token = localStorage.getItem('token');
        let ContentType
        if (type == 'json') {
            ContentType = 'application/json'
        } else if (type == 'form') {
            ContentType = 'application/x-www-form-urlencoded'
        }

        //请求头加签名
        let sign='';
        if(parmas){
            let newParams = {...parmas}
            newParams['appt'] = Date.parse(new Date())
            sign =this.herderParmasMd5(newParams);
        }else{
            sign =this.herderParmasMd5({app:'app', appt:Date.parse(new Date())});
        }

        return {
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': "*",
            'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers':'Authorization, tenantId',
            'Access-control-expose-headers': 'Authorization, tenantId',
            'tenantId': localStorage.getItem("tenantId"),
            'Content-Type': ContentType,
            'Authorization': token ? token : "Bearer ",
            'timestamp': Date.parse(new Date()),
            'sign': sign,
            'tenantId': localStorage.getItem('tenantId') ? localStorage.getItem('tenantId') : '',
        }
    }

    /**
     * 请求返回结构（业务数据返回为空或者错误时默认返回）
     */
    getResponse() {
        return {
            // 业务返回码(可选)
            code: null,
            // 返回信息
            msg: null,
            // 错误信息
            error: null,
            // 返回数据
            data: {}
        }
    }

    /**
     * 超时时间
     * @returns {number}
     */
    getTimeOut() {
        return 15000;
    }

    /**
     * 对象按照属性名的字母顺序进行排列
     * @param {*} obj
     */
    parmasKeySort(obj) {
        var newkey = Object.keys(obj).sort();
        var newObj = {};
        for (var i = 0; i < newkey.length; i++) {
            newObj[newkey[i]] = obj[newkey[i]];
        }
        return newObj;
    }
    /**
     * 在此处做参数排序以及MD5加密,添加到请求头
     * @param {*} parmas
     */
    herderParmasMd5(parmas){
        let herderParmas= '';
        parmas =  this.parmasKeySort(parmas);
        Object.keys(parmas).forEach(function(key){
            if (parmas[key] === undefined || parmas[key] === null || parmas[key] === 'undefined' || parmas[key] === '') {
                key= '';
                parmas[key]='';
            }
            herderParmas += key+parmas[key];
        });
        return md5(herderParmas);
    }

    /**
     * 在此处理参数加密
     * @param parmas
     * @param method GET or POST
     */
    encryption(parmas, method){
        if(method === 'POST'){
            //*********加密****************;
            let randomStr = this.randomString(16);
            // aes加密
            let data =this.Encrypt(JSON.stringify(parmas),randomStr);
            // rsa加密
            let encrypt = new JSEncrypt();
            encrypt.setPublicKey(publicKey);
            let encrypted = encrypt.encrypt(randomStr);
            let json = {
                "requestData": data,
                "encrypted": encrypted
            };
            parmas = json;
        }
        return parmas;
    }

    /**
     * 处理解密
     * @param json
     * @param method
     */
    decrypt(json, method){
        if(method === 'POST' && !json['code']) {
            //*************解密***************
            var decrypt = new JSEncrypt();
            decrypt.setPrivateKey(privateKey);
            var aesKey = decrypt.decrypt(json.encrypted);
            // 用aes秘钥进行解密
            var resultData = this.Decrypt(json.requestData,aesKey);
            json = JSON.parse(resultData)
        }
        return json;
    }

    /**
     * 获取16位随机字符串
     */
    randomString(len){
        len = len || 32;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = $chars.length;
        var pwd = '';
        for (let i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    /**
     * 加密，解密工具类
     */
    //key值，要和后端的key相同
    Encrypt(word,randomKey){
        let key = CryptoJS.enc.Utf8.parse(randomKey);
        var srcs = CryptoJS.enc.Utf8.parse(word);
        var encrypted = CryptoJS.AES.encrypt(srcs, key, {
            mode : CryptoJS.mode.ECB,
            padding : CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
    }

    Decrypt(word,randomKey) {
        let key = CryptoJS.enc.Utf8.parse(randomKey);
        var decrypt = CryptoJS.AES.decrypt(word, key, {
            mode : CryptoJS.mode.ECB,
            padding : CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Utf8.stringify(decrypt).toString();
    }

    /**
     * 用于规范化错误提示信息
     * @param serverError 服务器响应错误
     * @param businessErro 业务逻辑错误
     */
    constructor(serverError, businessErro) {
        this.serverError = serverError ? serverError : {
            404: '页面走丢了',
            403: '您被保安拦住了，请联系管理员',
            402: '世界崩塌了，请重新登录',
            uError: '未定义错误'
        }

        this.businessErro = businessErro ? businessErro : {

        }
    }

    /**
     * 系统错误检测
     * @param response
     * @returns {Promise|Promise<T>}
     */
    detect(response) {
        return new Promise((resolve, reject) => {
            switch (response.status) {
                case 200:
                    resolve(response);
                    break;
                case 201:
                    resolve(this.authorization(response));
                    break;
                case 249:
                    resolve(this.nginxOpen(response));
                    break;
                case 401:
                    resolve(this.tokenBusiness(response));
                    break;
                case 504:
                    resolve(this.overBusiness(response));
                    break;
                default:
                    // 非200的直接丢给错误断言自动处理
                    reject(this.tryError(response));
            }
        });
    }

    /**
     * 检测限流
     * @param response
     */
    nginxOpen(response) {
        window.location.href = 'http://twb.vgogbuy.cn/waiting/index.html'
        return response
    }

     /**
     * 授权处理
     * @param response
     */
    authorization(response) {
       let refUrl
       // 获取完授权写死回到首页
       localStorage.setItem('refUrl', '#/main');
       refUrl = localStorage.getItem('refUrl');

       // 登录成功后的回调页面
       let url = window.location.origin + window.location.pathname + refUrl;
        const token = response.headers.get('Authorization');
        localStorage.setItem('token', token);
        window.location.replace(url);
        return response;
    }

    /**
     * 业务错误检测
     * @param response
     */
    detectBusiness(response) {
        return new Promise((resolve, reject) => {
            switch (parseInt(response.code)) {
                case 250:
                    resolve(this.overBusiness(response));
                    break;
                default:
                    resolve(response);
            }
        });
    }
    /**
     * token过期或未登录检测
     * @param response
     */
    tokenBusiness(response) {
        localStorage.removeItem('token');
        loginServer.goAuth()
        return response
    }


    /**
     * 超时检测
     * @param response
     */
    overBusiness(response) {
        Toast.offline('请求超时, 请稍后重试~', 3)
        return response
    }

    /**
     * 错误自动断言
     * @param status
     * @returns {*}
     */
    tryError(response) {
        console.log('http request error! request address: '+ response.url + '\n' + 'code:' + response.status);
        let error = '';
        if(this.serverError[response.status.toString()])
            error = this.serverError[response.status.toString()];
        else
            error = this.serverError.uError;

        // 统一错误提示
        message.error(error);
        return error;
    }
}